/*
 * Copyright 2015 William Wang.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package wxk.Bonus.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.SSLContext;
import wxk.Bonus.Constant.DBContant;

/**
 * Created on : Jan 21, 2015 9:30:38 PM
 * @author William Wang
 */

public class Toolkit {
public String readFromJARFile(String filename)
throws IOException
{
 System.out.println("filename:"+filename);   
    ClassLoader CLDR = this.getClass().getClassLoader();
    InputStream is = CLDR.getResourceAsStream(filename);
    InputStreamReader isr = new InputStreamReader(is);
  BufferedReader br = new BufferedReader(isr);
  StringBuffer sb = new StringBuffer();
  String line;
  while ((line = br.readLine()) != null)
  {
    sb.append(line);
  }
  br.close();
  isr.close();
  is.close();
  return sb.toString();
}
/**
 * get data from web
 * @param url
 * @return 
 */
public String readFromWeb(String url)
{
    String responseBody="";

	CloseableHttpClient httpclient =null;
    try
    {
      KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());

       // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);//STRICT_HOSTNAME_VERIFIER
        httpclient= HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();

         HttpGet httpget = new HttpGet(url);
    	 
         ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

             public String handleResponse(
                     final HttpResponse response) throws ClientProtocolException, IOException {
                 int status = response.getStatusLine().getStatusCode();
                 if (status >= 200 && status < 300) {
                     HttpEntity entity = response.getEntity();
                     return entity != null ? EntityUtils.toString(entity) : null;
                 } else {
                     throw new ClientProtocolException("Unexpected response status: " + status);
                 }
             }

         };

         // Create a response handler
         if(httpclient!=null)
          responseBody = httpclient.execute(httpget, responseHandler);
     }
       catch(Exception e)
          {
           e.printStackTrace();	  
          }
      finally {
         // When HttpClient instance is no longer needed,
         // shut down the connection manager to ensure
         // immediate deallocation of all system resources
        if(httpclient!=null)
         httpclient.getConnectionManager().shutdown();
     }	
    return responseBody;
}
 public  ArrayList<String> parseUnionData1(String historydata)
	  {
		  ArrayList<String> result =new ArrayList<String>();
		  Pattern p = Pattern.compile(DBContant.DOUBLEBALL_PATTERN_1);
			Matcher m = p.matcher(historydata);
	    while(m.find())
	      {
	      	result.add(m.group());
	      	}   
	 	  return result;   	
	    }
	  public   String getCurrentTerm(String term,String historydata)
	  {
	  	long starttime=System.currentTimeMillis();
	    String result="";
	    String regular="("+term.trim()+")"+DBContant.DOUBLEBALL_PATTERN_TAIL;   	
	    BonusLogger.getInstance().log("regular:"+regular);
	      	long endtime=System.currentTimeMillis();
			Pattern p = Pattern.compile(regular);
			Matcher m = p.matcher(historydata);
	    while(m.find())
	      {
	      	result= m.group();
	      	}   
	    BonusLogger.getInstance().log("Cost(ms) "+(endtime-starttime));
	 	  return result;   	
	    }
public static boolean isNumeric(String str)
{
    return str.matches("[+-]?\\d*(\\.\\d+)?");
}           
public static String[] splitStr(String str)
{
 return str.split("[,\t-.]+");//splite,.-
}
}
